<script setup lang="ts">
import type { IRouteInfoResp } from '@/api/types'
import { onMounted, ref } from 'vue'
import { useSimpleRoute } from '@/hooks'
import BannerSwiper from './components/BannerSwiper.vue'
import GridMenu from './components/GridMenu.vue'
import SearchBar from './components/SearchBar.vue'
import SubRouteMenu from './components/sub/SubRouteMenu.vue'
import { useBanners, useGrids, useSearch } from './composable/useHome'

defineOptions({
  name: 'Home',
})

definePage({
  type: 'home',
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '首页',
  },
})

const { handleSearch } = useSearch()
const { banners, handleBannerClick } = useBanners()
const { grids, handleGridClick: originalHandleGridClick, loading: gridsLoading } = useGrids()
const { routes } = useSimpleRoute()

// 子路由菜单状态
const showSubRouteMenu = ref(false)
const currentSelectedRoute = ref<IRouteInfoResp | null>(null)

// 处理宫格点击，检查是否有子路由
function handleGridClick(item: any) {
  // 从路由数据中找到对应的路由信息
  const route = routes.value.find(r => r.path === item.url || r.id === item.id)

  if (route && route.children && route.children.length > 0) {
    // 有子路由，显示子路由菜单
    currentSelectedRoute.value = route
    showSubRouteMenu.value = true
  }
  else {
    // 没有子路由，使用原来的跳转逻辑
    originalHandleGridClick(item)
  }
}

// 使用图表数据

// 处理子路由点击
function handleSubRouteClick(route: IRouteInfoResp) {
  if (route.path) {
    uni.navigateTo({ url: route.path })
  }
  // 点击后关闭子路由菜单
  handleSubRouteMenuClose()
}

// 处理子路由菜单关闭
function handleSubRouteMenuClose() {
  showSubRouteMenu.value = false
  currentSelectedRoute.value = null
}

// 页面加载时初始化数据
onMounted(() => {
  // 加载路由数
})
</script>

<template>
  <view class="min-h-screen from-blue-100 to-purple-100 bg-gradient-to-b">
    <!-- 状态栏占位 -->
    <view class="h-20" />

    <!-- 搜索框 -->
    <SearchBar @search="handleSearch" />

    <!-- 轮播图 -->
    <BannerSwiper :banners="banners" @click="handleBannerClick" />

    <!-- 宫格菜单 -->
    <GridMenu :grids="grids" :loading="gridsLoading" @click="handleGridClick" />

    <!-- 子路由菜单 -->
    <SubRouteMenu
      v-model:visible="showSubRouteMenu"
      :current-route="currentSelectedRoute"
      :all-routes="routes"
      @route-click="handleSubRouteClick"
      @close="handleSubRouteMenuClose"
    />
  </view>
</template>

<style scoped>
/* 仅用于UnoCSS无法实现的样式 */
</style>
